import React, { useState, ReactElement } from 'react';

import Axios from 'axios';
import { AutoComplete } from 'choerodon-ui';
import { OptionProps } from 'choerodon-ui/lib/select';
import { Data } from './typing.d';

const { Option } = AutoComplete;
const { OptGroup } = AutoComplete;

function renderTitle(title: string) {
  return (
    <span>
      {title}
      <a
        style={{ float: 'right' }
        }
        href="https://www.google.com/search?q=choerodon"
        target="_blank"
        rel="noopener noreferrer"
      > 更多
      </a>
    </span>
  );
}

export const useAutoCompleteBasic = (): [ReactElement<OptionProps>[], (value: string) => void] => {
  const [outOptions, setOptions] = useState<ReactElement<OptionProps>[]>([]);

  const handleSearch = (value: string) => {
    Axios.get<any, Data[]>('/_api/auto-complete-certain-category', {
      params: {
        value,
      },
    })
      .then(res => {
        const dataSource = res || [];
        const options = dataSource.map(group => (
          <OptGroup
            key={group.title}
            label={renderTitle(group.title)}
          >
            {
              group.children?.map(opt => (
                <Option key={opt.title} value={opt.title}>
                  {opt.title}
                  <span className="certain-search-item-count"> {opt.count} 人 关注 </span>
                </Option>
              ))
            }
          </OptGroup>
        ));
        setOptions(options);
      });
  };
  return [outOptions, handleSearch];
};